package com.smartrobot.smartrobot.DB;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.smartrobot.smartrobot.logToSdCard.LogToSd;
import com.smartrobot.smartrobot.pojo.NewFriendPojo;
import com.smartrobot.smartrobot.pojo.getFriendListPojo;
import com.smartrobot.smartrobot.pojo.saveFriendListPojo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by yeluojun on 2015/1/21.
 */
public class FriendListSqlHelper {

    /* 日志的标志 */
    private static final String TAG = "sqlite for new friend_list";

    /*创建新的朋友的数据库*/
    public static final  String CREATE_FRIEND_LIST_DB = "create table friend_list( id INTEGER primary key autoincrement ," +
            "userId varchar(255) ,headImg varchar(255) ,name varchar(255),nickname varchar(255)" +
            ",sex varchar(255),role varchar(12),userAccount varchar(255),sign varchar(255),status varchar(255),editTime varchar(255),userType varchar(255))";



    /*数据库的名字*/
    private static  String DB_NAME = "SmartRobot";

    /*表名字*/
    public static  final String TABLE_NAME = "friend_list";

    /*数据库版本*/
    static final int DATABASE_VERSION = 1;


    /*数据库的字段*/
    public static final String USER_ID = "userId";
    public static final String HEAD_IMG = "headImg";
    public static final String USER_NAME = "name";
    public static final String NICKNAME = "nickname";
    public static final String SEX = "sex";
    public static final String ROLE = "role";
    public static final String USER_ACCOUNT = "userAccount";
    public static final String SIGN = "sign";
    public static final String STATUS = "status";
    public static final String EDIT_TIME = "editTime";
    public static final String USER_TYPE = "userType";



    /*数据标志*/
    public static final String BARBER = "my_barber";
    public static final String FRIEND = "my_friend";
    public static final String CIRCLE = "my_circle";



    Context context;

    SQLiteDatabase db;

    DatabaseHelper DBHelper;


    public FriendListSqlHelper(Context cxt,String db_name)
    {
        this.context = cxt;
        DB_NAME = db_name+"_"+TABLE_NAME;
        DBHelper = new DatabaseHelper(context);
    }


    private static class DatabaseHelper extends SQLiteOpenHelper
    {

        DatabaseHelper(Context context)
        {
            super(context, DB_NAME, null, DATABASE_VERSION);
        }
        @Override
        public void onCreate(SQLiteDatabase db) {

            try
            {
                db.execSQL(CREATE_FRIEND_LIST_DB);
                Log.e("======创建数据库=======","成功!");
            }
            catch(SQLException e)
            {

                Log.w("=======创建数据库失败=======", e.toString());
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            Log.e(TAG, "Upgrading database from version " + oldVersion + "to " +
                    newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME );
        }
    }


    public FriendListSqlHelper open() throws SQLException
    {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    public void close()
    {
        DBHelper.close();
    }



    /*插入数据库*/
    public synchronized long   insertFriendList(getFriendListPojo pojo,String userType)
    {
        Date date = new Date();

        ContentValues initialValues = new ContentValues();
        initialValues.put(USER_ID, pojo.getUserId());
        initialValues.put(HEAD_IMG, pojo.getHeadImg());
        initialValues.put(USER_NAME, pojo.getReName());
        initialValues.put(NICKNAME, pojo.getName());
        initialValues.put(SEX, pojo.getSex());
        initialValues.put(ROLE, pojo.getRole());
        initialValues.put(USER_ACCOUNT, pojo.getUserAccount());
        initialValues.put(SIGN,pojo.getSign());
        initialValues.put(STATUS,"NORMAL");
        initialValues.put(EDIT_TIME, date.getTime()+"");
        initialValues.put(USER_TYPE, userType);
        return db.insert(TABLE_NAME, null, initialValues);
    }

    /*插入全部数据*/
    public synchronized boolean insertAllFriendList(saveFriendListPojo pojos){
        boolean suc = true;
        try{

            db.beginTransaction();

            if(pojos.getBarberList()!=null){
                for(int i=0;i<pojos.getBarberList().size();i++){
                    insertFriendList(pojos.getBarberList().get(i),BARBER);
                }
            }

            if(pojos.getFriendList()!=null){
                for(int i=0;i<pojos.getFriendList().size();i++){
                    insertFriendList(pojos.getFriendList().get(i),FRIEND);
                }
            }

            if(pojos.getCircleList()!=null){
                for(int i=0;i<pojos.getCircleList().size();i++){
                    insertFriendList(pojos.getCircleList().get(i),CIRCLE);
                }
            }
            db.setTransactionSuccessful(); //设置事务处理成功，不设置会自动回滚不提交。


        }catch ( Exception e){
            suc = false;
            Log.e("插入朋友圈的朋友列表失败:",e.toString());
            LogToSd.log_init();
            LogToSd.error("插入朋友圈的朋友列表失败");
            LogToSd.error(e.toString());



        }finally {
            db.endTransaction(); //处理完成
        }

        return true;

    }



    /*删除数据*/
    public synchronized boolean deleteFromNewFriend(String userId){
        try{
            db.delete(TABLE_NAME, USER_ID + "=" +userId, null);
            return true;
        }catch (Exception e){
            return false;
        }

    }

    /*删除所有数据*/
    public synchronized boolean deleteAllFromNewFriend(){
        try {
            db.execSQL("delete from "+TABLE_NAME);
            return true;
        }catch (Exception e){
            return false;
        }
    }


    /*查找数据--显示全部*/
    public saveFriendListPojo searchAllFromFriendList(){
        try{
            List<getFriendListPojo> barberList = new ArrayList<getFriendListPojo>();
            List<getFriendListPojo> friendList = new ArrayList<getFriendListPojo>();
            List<getFriendListPojo> circleList = new ArrayList<getFriendListPojo>();
            String[] args = {String.valueOf("NORMAL")};
            Cursor cursor = db.rawQuery("select * from " + TABLE_NAME + " where status= ? order by editTime desc",args);

            if(cursor.getCount()<=0){
                cursor.close();
                return null;
            }

            while(cursor.moveToNext()){
                getFriendListPojo pojo = new getFriendListPojo();
                String userId = cursor.getString(cursor.getColumnIndex(USER_ID));
                String username = cursor.getString(cursor.getColumnIndex(USER_NAME));
                String nickname = cursor.getString(cursor.getColumnIndex(NICKNAME));
                String headImg = cursor.getString(cursor.getColumnIndex(HEAD_IMG));
                String userAccount = cursor.getString(cursor.getColumnIndex(USER_ACCOUNT));
                String sex = cursor.getString(cursor.getColumnIndex(SEX));
                String role = cursor.getString(cursor.getColumnIndex(ROLE));
                String sign = cursor.getString(cursor.getColumnIndex(SIGN));
                String userType = cursor.getString(cursor.getColumnIndex(USER_TYPE));

                pojo.setUserId(userId);
                pojo.setReName(username);
                pojo.setHeadImg(headImg);
                pojo.setUserAccount(userAccount);
                pojo.setRole(role);
                pojo.setSex(sex);
                pojo.setSign(sign);
                pojo.setName(nickname);

                if(userType.equals(BARBER)){
                    barberList.add(pojo);
                }else if(userType.equals(FRIEND)){
                    friendList.add(pojo);
                }else if(userType.equals(CIRCLE)){
                    circleList.add(pojo);
                }
            }
            cursor.close();
            saveFriendListPojo pojos  = new saveFriendListPojo(barberList,friendList,circleList);
            return pojos;
        }catch (Exception e){
            LogToSd.log_init();
            LogToSd.error("读取好友列表出错");
            LogToSd.error(e.toString());
            return null;
        }


    }

   /*查找单条数据*/

    public synchronized getFriendListPojo getFriendMsg(String user_account){
        db = DBHelper.getWritableDatabase();
        getFriendListPojo pojo = new getFriendListPojo();
        String[] args = {String.valueOf(user_account)};
        Cursor cursor = db.rawQuery("select * from " + TABLE_NAME + " where status='NORMAL' and " +USER_ACCOUNT +"=?",args);
        while(cursor.moveToNext()){

            String userId = cursor.getString(cursor.getColumnIndex(USER_ID));
            String username = cursor.getString(cursor.getColumnIndex(USER_NAME));
            String nickname = cursor.getString(cursor.getColumnIndex(NICKNAME));
            String headImg = cursor.getString(cursor.getColumnIndex(HEAD_IMG));
            String userAccount = cursor.getString(cursor.getColumnIndex(USER_ACCOUNT));
            String sex = cursor.getString(cursor.getColumnIndex(SEX));
            String role = cursor.getString(cursor.getColumnIndex(ROLE));
            String sign = cursor.getString(cursor.getColumnIndex(SIGN));
            String userType = cursor.getString(cursor.getColumnIndex(USER_TYPE));

            pojo.setUserId(userId);
            pojo.setReName(username);
            pojo.setHeadImg(headImg);
            pojo.setUserAccount(userAccount);
            pojo.setRole(role);
            pojo.setSex(sex);
            pojo.setSign(sign);
            pojo.setName(nickname);
        }
        cursor.close();
        db.close();
        return pojo;
    }

    /*判断数据是否存在*/
    public Boolean ifExist(String userId){
        Boolean exist = false;
        String[] args = {String.valueOf(userId)};
        Cursor cursor = db.rawQuery("select userId from " + TABLE_NAME + " where userId = ? ",args);
        int count = cursor.getCount();
        if (count>0){
            exist = true;
        }
        cursor.close();

        return exist;
    }


}
